from configs import ALGORITHM, SECRET_KEY, GO_SERVICE_SECRET_KEY
from fastapi import Body, Request
from server.utils import decode_token, decode_verify_token
from server.knowledge_base.kb_doc_api import delete_docs_func
from jose import JWTError
from server.utils import BaseResponse
from configs.logging_config import configure_logging
from loguru import logger
from server.db.repository.knowledge_file_repository import add_delete_training_content_log_to_db, file_exists_in_db_, get_file_name_hash_from_db
from server.knowledge_base.utils import get_file_path
import os

async def del_training_content(
        uid: str = Body(..., description="用户ID"),
        content: str = Body(..., description="要删除的训练内容，也就是文件名"),
        delete_content: bool = Body(True, description="是否删除训练内容的文件"),
        request: Request = None,
):
    token = request.headers.get("Authorization")
    if not token:
        logger.error(f"没有token")
        return BaseResponse(code=401, msg="没有token")
    try:
        payload = decode_token(token, SECRET_KEY, ALGORITHM)
        token_uid = payload.get("sub")
        if not token_uid:
            logger.error(f"Token中没有用户ID")
            return BaseResponse(code=401, msg="Token中没有用户ID")
        if token_uid != uid:
            logger.error(f"Token解析到的用户ID与请求的用户ID不一致")
            return BaseResponse(code=401, msg="Token解析到的用户ID与请求的用户ID不一致")
    except JWTError as e:
        logger.error(f"Token解析失败: {e}")
        return BaseResponse(code=401, msg="Token解析失败", data={"error": str(e)})
    try:
        if file_exists_in_db_(kb_name=uid, filename=content + ".txt"):
            # 获取文件名hash值
            file_name_hash = get_file_name_hash_from_db(kb_name=uid, filename=content + ".txt")["file_name_hash"]
            if file_name_hash:
                local_file_path = get_file_path(knowledge_base_name=uid, doc_name=file_name_hash)
                if os.path.exists(local_file_path):
                    os.remove(local_file_path)
        info = delete_docs_func(knowledge_base_name=uid, delete_content=delete_content, file_names=[f"{content}.txt"])
        if info["status"]:
            add_delete_training_content_log_to_db(uid, True, content)
            logger.info(f"用户 {uid} 删除训练内容 {content} 成功")
            return BaseResponse(code=200, msg=info["msg"], data={"deleted_file": info["failed_file"]})
        else:
            add_delete_training_content_log_to_db(uid, False, content)
            logger.error(f"用户 {uid} 删除训练内容失败: {info['msg']}, 失败的文件: {info['failed_file']}")
            return BaseResponse(code=500, msg=info["msg"], data={"failed_file": info["failed_file"]})
    except Exception as e:
        add_delete_training_content_log_to_db(uid, False, content)
        logger.error(f"删除训练内容失败: {e}")
        return BaseResponse(code=500, msg="删除训练内容失败", data={"error": str(e)})


async def del_training_content_v2(
        uid: str = Body(..., description="用户ID"),
        content: str = Body(..., description="要删除的训练内容，也就是文件名"),
        delete_content: bool = Body(True, description="是否删除训练内容的文件"),
        request: Request = None,
):
    # 解码token
    try:
        token = decode_verify_token(request, GO_SERVICE_SECRET_KEY, ALGORITHM)
    except Exception as e:
        return BaseResponse(code=401, msg="Token is invalid", data={"error": str(e.detail.get('msg'))})
    try:
        if file_exists_in_db_(kb_name=uid, filename=content + ".txt"):
            # 获取文件名hash值
            file_name_hash = get_file_name_hash_from_db(kb_name=uid, filename=content + ".txt")["file_name_hash"]
            if file_name_hash:
                local_file_path = get_file_path(knowledge_base_name=uid, doc_name=file_name_hash)
                if os.path.exists(local_file_path):
                    os.remove(local_file_path)
        info = delete_docs_func(knowledge_base_name=uid, delete_content=delete_content, file_names=[f"{content}.txt"])
        if info["status"]:
            add_delete_training_content_log_to_db(uid, True, content)
            logger.info(f"用户 {uid} 删除训练内容 {content} 成功")
            return BaseResponse(code=200, msg=info["msg"], data={"deleted_file": info["failed_file"]})
        else:
            add_delete_training_content_log_to_db(uid, False, content)
            logger.error(f"用户 {uid} 删除训练内容失败: {info['msg']}, 失败的文件: {info['failed_file']}")
            return BaseResponse(code=500, msg=info["msg"], data={"failed_file": info["failed_file"]})
    except Exception as e:
        add_delete_training_content_log_to_db(uid, False, content)
        logger.error(f"删除训练内容失败: {e}")
        return BaseResponse(code=500, msg="删除训练内容失败", data={"error": str(e)})
